package com.znz.domain;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

@RooJavaBean
@RooToString
@RooJpaActiveRecord(versionField="",identifierColumn = "id", identifierField = "id",table = "t_resource")
public class Resource implements Serializable{

    private String resourceName;
    private String resourceUrl;
    @ManyToOne
    @JoinColumn(name = "resource_type")
    private DictionaryDetail resourceType;
    private String resourceDomain;

    @ManyToOne
    @JoinColumn(name = "resource_level")
    private DictionaryDetail resourceLevel;
    @ManyToOne
    @JoinColumn(name = "parent_id")
    private Resource parentId;
    private int orderNumber;
    private String resourceIcon;
    private int isOpen;
    private int operator;
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    @Temporal(TemporalType.TIMESTAMP)
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    @JsonIgnore
    private Date createTime;
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    @Temporal(TemporalType.TIMESTAMP)
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    @JsonIgnore
    private Date updateTime;
    private int validPeriod;
    private int status;

    /**
     * 根据参数查询资源信息，参数的key对应的是字典实体的属性名，不是数据库的字段名
     * @param params
     * @return
     * @throws Exception
     */
    public static List<Resource> findResourceListByParams(String where,List<Object> params) throws Exception{
        StringBuilder str_query =  new StringBuilder("SELECT o FROM Resource o where o.status!=-1 ");
        str_query.append(where);
        str_query.append(" order by o.id ");
        if(params!=null){
            TypedQuery<Resource> q = entityManager().createQuery(
                    str_query.toString(), Resource.class);
            int i=1;
            for(Object key :params){
                q.setParameter(i,key);
                i++;
            }
            return q.getResultList();
        }
        return null;
    }

}
